<?php

namespace common\models\base;

use common\component\BaseActiveRecord;
use Yii;
use yii\behaviors\TimestampBehavior;

/**
 * This is the model class for table "{{%base_attachment}}".
 *
 * @property string $id
 * @property string $original 原始名
 * @property string $path 文件路径
 * @property string $name 文件名
 * @property string $ext 扩展名
 * @property string $size 文件大小
 * @property int $status 状态
 * @property string $created_at 创建时间
 */
class Attachment extends BaseActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{base_attachment}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['size', 'status', 'created_at'], 'integer'],
            [['original', 'name'], 'string', 'max' => 64],
            [['path'], 'string', 'max' => 127],
            [['ext'], 'string', 'max' => 8],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'original' => '原始名',
            'path' => '路径',
            'name' => '文件名',
            'ext' => '扩展名',
            'size' => '大小',
            'status' => '状态',
            'created_at' => '创建时间',
        ];
    }

    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    self::EVENT_BEFORE_INSERT => ['created_at']
                ]
            ]
        ];
    }

    public static function loadRowData($id) {
        return self::findOne($id);
    }

    public function attachUrl($size = "") {
        if (empty($size)) {
            return Yii::$app->params['attach.image.url'].$this->path.DIRECTORY_SEPARATOR.$this->name.$this->ext;
        }
        return Yii::$app->params['attach.image.url'].$this->path.DIRECTORY_SEPARATOR.$this->name."_{$size}".$this->ext;
    }

    /**
     * 清空数据和文件
     * @param $id
     * @return bool
     */
    public static function removeDataAndFile($id) {
        $model = static::findOne($id);
        if (!$model) return false;
        $realPath = Yii::$app->params['attach.image.path'].$model->path;
        if (file_exists($realPath)) {
            $files = glob($realPath.DIRECTORY_SEPARATOR.$model->name."*".$model->ext);
            foreach ($files as $file) {
                if (file_exists($file)) {
                    unlink($file);
                }
            }
        }
        return $model->delete();
    }

}
